import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

// 状态转换规则
const STATUS_TRANSITIONS = {
  'DRAFT': ['REVIEW', 'ARCHIVED'],
  'REVIEW': ['APPROVED', 'DRAFT'],
  'APPROVED': ['RELEASED', 'REVIEW'],
  'RELEASED': ['ARCHIVED'],
  'ARCHIVED': ['DRAFT']
}

// 状态描述映射
const STATUS_DESCRIPTIONS = {
  'DRAFT': '草稿',
  'REVIEW': '审核中',
  'APPROVED': '已批准',
  'RELEASED': '已发布',
  'ARCHIVED': '已归档'
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const body = await request.json()
    const { 
      level1, 
      level2, 
      level3, 
      level4, 
      statusDesc, 
      updatedBy, 
      comment,
      updateAllLevels = false // 是否更新所有级别
    } = body
    
    const existingProject = await db.researchProject.findUnique({
      where: { id: (await params).id }
    })
    
    if (!existingProject) {
      return NextResponse.json(
        { error: 'Research project not found' },
        { status: 404 }
      )
    }
    
    // 验证状态转换是否合法（仅当一级状态改变时）
    if (level1 && level1 !== existingProject.level1) {
      const allowedTransitions = STATUS_TRANSITIONS[existingProject.level1 as keyof typeof STATUS_TRANSITIONS] || []
      if (!allowedTransitions.includes(level1)) {
        return NextResponse.json(
          { error: `Cannot transition from ${existingProject.level1} to ${level1}` },
          { status: 400 }
        )
      }
    }
    
    const updateData: any = {
      updatedBy,
      updateTime: new Date()
    }
    
    // 更新状态数据
    if (level1 !== undefined) updateData.level1 = level1
    if (level2 !== undefined) updateData.level2 = level2
    if (level3 !== undefined) updateData.level3 = level3
    if (level4 !== undefined) updateData.level4 = level4
    if (statusDesc !== undefined) updateData.statusDesc = statusDesc
    
    // 更新状态时间（仅当一级状态改变时）
    if (level1 && level1 !== existingProject.level1) {
      updateData.stateTime = new Date()
      
      // 设置状态过期时间（根据不同状态设置不同的过期时间）
      const expireDays = {
        'DRAFT': 30,
        'REVIEW': 7,
        'APPROVED': 90,
        'RELEASED': 365,
        'ARCHIVED': null
      }
      
      if (expireDays[level1 as keyof typeof expireDays]) {
        const expireDate = new Date()
        expireDate.setDate(expireDate.getDate() + expireDays[level1 as keyof typeof expireDays]!)
        updateData.stateExpireTime = expireDate
      }
    }
    
    const project = await db.researchProject.update({
      where: { id: (await params).id },
      data: updateData,
      include: {
        creator: {
          select: {
            id: true,
            name: true,
            email: true
          }
        },
        updater: {
          select: {
            id: true,
            name: true,
            email: true
          }
        }
      }
    })
    
    // 创建历史记录
    const historyData: any = {
      projectId: project.id,
      action: 'STATUS_CHANGED',
      description: comment || `状态变更为 ${STATUS_DESCRIPTIONS[level1 as keyof typeof STATUS_DESCRIPTIONS] || level1}`,
      userId: updatedBy,
      fromLevel1: existingProject.level1,
      fromLevel2: existingProject.level2,
      fromLevel3: existingProject.level3,
      fromLevel4: existingProject.level4,
      toLevel1: project.level1,
      toLevel2: project.level2,
      toLevel3: project.level3,
      toLevel4: project.level4
    }
    
    await db.projectHistory.create({
      data: historyData
    })
    
    return NextResponse.json(project)
  } catch (error) {
    console.error('Error updating project status:', error)
    return NextResponse.json(
      { error: 'Failed to update project status' },
      { status: 500 }
    )
  }
}